import os
from threading import Thread
from datetime import datetime
from AutoRegister.settings import LOG_DIR
from models.models import OntRecord


def async_method(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
        thr.start()

    return wrapper


@async_method
def write_log(data, ip, port, userrole=None, level=None):
    file_path = LOG_DIR / f'{ip}_{port}'
    if not file_path.exists():
        file_path.mkdir()

    if userrole:
        file_name = "%s_%s_%s_%srun.log" % (ip, port, str(datetime.now())[:10], userrole)
    else:
        file_name = "%s_%s_%srun.log" % (ip, port, str(datetime.now())[:10])

    file = os.path.join(file_path, file_name)
    with open(file, "a", encoding='utf-8') as f:
        f.write("%s  " % str(datetime.now())[:19])
        f.write(data)
        f.write("\n")

    # 错误日志
    if level == "error":
        file_name = "%s_%s_%serror.log" % (ip, port, str(datetime.now())[:10])
        file = os.path.join(file_path, file_name)
        with open(file, "a") as f:
            f.write("%s  " % str(datetime.now())[:19])
            f.write(data)
            f.write("\n")
    return True


def Save_OntRecord(olt_id, equipment, community, olt_type, register_type, frameid, slotid, board_port, ont_num, sn,
                   line_template, business_template, business_intimal, business_outer, gemport):
    OntRecord.objects.create(olt_id=olt_id,
                             equipment=equipment,
                             community=community,
                             olt_type=olt_type,
                             register_type=register_type,
                             frameid=frameid,
                             slotid=slotid,
                             board_port=board_port,
                             ont_num=ont_num,
                             sn=sn,
                             line_template=line_template,
                             business_template=business_template,
                             business_intimal=business_intimal,
                             business_outer=business_outer,
                             gemport=gemport,
                             created_time=datetime.now()
                             )
    return
